<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片列表 -->
    <el-card>
      <el-row>
        <el-button type="primary">添加角色</el-button>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="rolesList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scoped">
            <!-- 循环展开项 -->
            <el-row
              v-for="(item1, i1) in scoped.row.children"
              :key="item1.id"
              :class="['bottom-border', i1 === 0 ? 'top-border' : '']"
              class="vcenter"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removerightid(scoped.row, item1.id)">
                  {{ item1.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二三级权限 -->
              <el-col :span="19">
                <!-- for循环渲染二级权限 -->
                <el-row
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                  :class="[i2 === 0 ? '' : 'top-border']"
                  class="vcenter"
                >
                  <el-col :span="6">
                    <el-tag
                      closable
                      type="success"
                      @close="removerightid(scoped.row, item2.id)"
                    >
                      {{ item2.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- for循环三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="(item3, i3) in item2.children"
                      :key="item3.id"
                      closable
                      @close="removerightid(scoped.row, item3.id)"
                      >{{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scoped">
            <el-button size="mini" type="primary" icon="el-icon-edit"
              >编辑</el-button
            >
            <el-button size="mini" type="danger" icon="el-icon-delete"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="getrighttree(scoped.row)"
              >分配</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限的对话框 -->
    <el-dialog
      title="权限分配"
      :visible.sync="rightdialogVisible"
      width="50%"
      @close="setRightDialogclosed"
    >
      <!-- 树形权限控件 -->
      <el-tree
        :data="rightList"
        :props="rightProps"
        show-checkbox
        node-key="id"
        default-expand-all
        highlight-current
        :default-checked-keys="treearr"
        ref="terrRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rightdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 角色列表数据
      rolesList: [],
      // 控制对话框的显示与隐藏
      rightdialogVisible: false,
      // 获取到的权限列表数据
      rightList: [],
      // 树形权限绑定
      rightProps: {
        label: "authName",
        children: "children",
      },
      treearr: [],
      // 当前即将分配权限的角色id
      roleid: "",
    };
  },
  created() {
    this.getrolesList();
  },
  methods: {
    async getrolesList() {
      const { data: res } = await this.$http.get("roles");
      //   console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error("获取数据失败");
      }
      this.rolesList = res.data;
      //   console.log(this.rolesList);
    },
    async removerightid(role, right) {
      const confirmResould = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmResould !== "confirm") {
        return this.$message.info("取消成功");
      }
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${right}`
      );
      if (res.meta.status !== 200) {
        return this.$message.error("删除用户失败");
      }
      this.$message.success("删除用户成功");
      role.children = res.data;
    },
    //权限分配列表
    async getrighttree(role) {
      this.roleid = role.id;
      const { data: res } = await this.$http.get("rights/tree");
      if (res.meta.status !== 200) {
        return this.$message.error("获取权限列表失败");
      }
      this.rightList = res.data;
      // console.log(this.rolesList)
      this.getLeafKeys(role, this.treearr);
      this.rightdialogVisible = true;
    },
    // 递归函数  通过递归的形式获取所有角色的三级ID  保存到数组中
    getLeafKeys(role, arr) {
      // 获取三级角色的ID
      if (!role.children) {
        return arr.push(role.id);
      }
      // 循环不是三级角色的ID
      role.children.forEach((item) => this.getLeafKeys(item, arr));
    },
    // 监听权限对话框的关闭事件
    setRightDialogclosed() {
      this.treearr = [];
    },
    //点击位角色分配权限
    async allotRights() {
      const keys = [
        ...this.$refs.terrRef.getCheckedKeys(),
        ...this.$refs.terrRef.getHalfCheckedKeys(),
      ];
      // console.log(keys)
      const idstr = keys.join(",");
      const { data: res } = await this.$http.post(
        `roles/${this.roleid}/rights`,
        { rids: idstr }
      );
      if(res.meta.status!==200){
        return this.$message.error('更新权限失败')
      }
      this.$message.success('分配权限成功')
      this.getrolesList()
      this.rightdialogVisible=false

    },
  },
};
</script>

<style lang="less" socped>
.el-tag {
  margin: 7px;
}
.top-border {
  border-top: 1px solid #eee;
}
.bottom-border {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>